<template>
  <div>
    <el-dialog title="文件管理"
               :visible.sync="fileDialogVisible"
               width="80%" @close="closeDialog">
      <div class="table-container">

        <div style="width: 100%;text-align: right;padding: 20px 0">
          <el-button size="mini" @click="getList" type="primary">查询</el-button>
          <el-upload style="display: inline" v-if="hasUpdatePermission" class="upload-demo"
                     ref="fileUpload"
                     action=""
                     :limit="1"
                     :before-upload="beforeFileUpload"
                     :on-exceed="handleFileExceed"
                     :http-request="function(file){return handleFileUpload(file);}">
            <el-button size="mini" type="primary">添加文件</el-button>
          </el-upload>
        </div>
        <el-table :data="fileList"
                  style="width: 100%;"
                  v-loading="fileListLoading" border>
          <el-table-column label="文件ID" align="center" prop="id" show-overflow-tooltip/>
          <el-table-column label="文件名称" align="center" prop="fileName" show-overflow-tooltip/>
          <el-table-column label="文件大小" align="center" prop="fileSize">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="上传者" prop="uploadUser"/>
          <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip/>
          <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip/>

          <el-table-column label="操作" align="center" width="330">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handlePreviewFile(scope.row)">预览</el-button>
              <el-button size="mini" type="success" @click="handlePreviewFile(scope.row,'newTag')">新窗口预览</el-button>
              <el-button size="mini" type="primary" @click="handleDownloadFile(scope.row.id)">下载</el-button>
              <el-button v-if="hasUpdatePermission" size="mini" type="danger" @click="handleDeleteFile(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="small">取 消</el-button>
      </span>
    </el-dialog>

    <file-preview :fileId="fileId" :fileName="fileName"
                  :visible="previewVisible" @close="previewVisible =false"></file-preview>
  </div>
</template>

<script>
import {sysFileDownload, sysFilePostRequire, sysFilePostRequireByConfig} from '@/api/sysFile'
import store from '@/store'
import FilePreview from "@/views/component/filePreview";

export default {
  components: {FilePreview},
  name: "fileManager",
  props: {
    fileKeys: {
      default: ""
    },
    updateObject: {
      default: {}
    },
    visible: {
      default: false
    },
  },
  data() {
    return {
      previewVisible:false,
      fileId:'',
      fileName:'',

      fileDialogVisible: false,
      fileList: [],
      hasUpdatePermission: false,
      fileListLoading: false,
    }
  },
  watch: {
    visible(val) {
      this.fileDialogVisible = val
      if (val) {
        this.refresh()
      }
    },
  },
  mounted() {
    let allResource = store.getters.allResource || []
    this.hasUpdatePermission = allResource.indexOf("sysFile:add") !== -1
  },
  methods: {
    formatFileSize(size) {
      if (!size) {
        return '-'
      }
      size = parseInt(size) / 1024
      if (size < 1000) {
        return size.toFixed(2) + " KB"
      }
      size = size / 1024
      if (size < 1000) {
        return size.toFixed(2) + " MB"
      }
      size = size / 1024
      return (size / 1024).toFixed(2) + " GB"
    },
    refresh() {
      this.getList()
    },
    getList() {
      this.fileListLoading = true
      let fileIds = this.updateObject[this.fileKeys] || ''
      if (!fileIds) {
        this.fileListLoading = false
        this.fileList = []
        return;
      }
      sysFilePostRequire('getAllByIds', {fileIds: fileIds}).then(response => {
        this.fileListLoading = false
        this.fileList = response.data
      })
    },
    closeDialog() {
      this.fileDialogVisible = false
      this.$emit('close')
    },
    beforeFileUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isLt5M;
    },
    handleFileExceed() {
      this.$message({
        message: "只能选择一个文件",
        type: 'error'
      })
    },
    handleFileUpload(file) {
      const that = this;
      let params = new FormData()
      params.append("file", file.file);
      let headers = {
        'Content-Type': 'multipart/form-data; name="file"'
      }
      sysFilePostRequireByConfig('uploadFile', params, headers).then(response => {
        let fileId = response.data.id
        let fileIds = this.updateObject[this.fileKeys] || ''
        if (fileIds) {
          fileIds += "," + fileId
        } else {
          fileIds = fileId
        }
        let updateObject = this.$deepClone( this.updateObject)
        updateObject[this.fileKeys] = fileIds
        that.$emit("updateFile", 'update', updateObject, (response) => {
          if (response) {
            that.$message({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
            if (response.status) {
              this.updateObject[this.fileKeys] = fileIds
              that.getList()
              this.$refs.fileUpload.clearFiles()
            }
          }
        })
      })
    },

    handleDownloadFile(id) {
      sysFileDownload("downloadPersonalFile", {fileId: id}).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      })
    },
    handleDeleteFile(id) {
      this.$confirm('是否要删除该文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.fileListLoading = true
        sysFilePostRequire('deletePersonalById', {id: id}).then((response) => {

          if (response) {
            this.$message({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
            if (!response.status) {
              return;
            }
          }

          let fileIds = this.updateObject[this.fileKeys] || ''
          let fileIdsArr = fileIds.split(",")
          let deleteIndex = -1
          for (let i = 0; i < fileIdsArr.length; i++) {
            if (fileIdsArr[i] == id) {
              deleteIndex = i;
              break;
            }
          }
          if (deleteIndex >= 0) {
            fileIdsArr.splice(deleteIndex, 1)
            fileIds = fileIdsArr.join(",")
          }
          let updateObject = this.$deepClone( this.updateObject)
          updateObject[this.fileKeys] = fileIds
          this.$emit("updateFile", 'update', updateObject, (response1) => {
            if (response1) {
              this.$message({
                message: response1.message,
                type: response1.status ? 'success' : 'error'
              })
              if (response1.status) {
                this.updateObject[this.fileKeys] = fileIds
                this.getList()
              }
            }
          })
          this.fileListLoading = false

        })
      })

    },
    handlePreviewFile(row,openType) {
      let name =row.fileName
      if (openType){
        window.open(window.origin+'/#/filePreview?fileId='+row.id+"&fileName="+encodeURIComponent(name),"_blank");
      }else{
        this.fileId = row.id
        this.previewVisible = true
        this.fileName = name
      }
    },
  }
}
</script>

<style scoped>

</style>
